package com.mdata.controller;

import com.mdata.common.DefinitionException;
import com.mdata.model.po.CacheUser;
import com.mdata.common.RedisKeyConstant;
import com.mdata.common.ResponseEnum;
import com.mdata.common.ResultData;
import com.mdata.model.po.SubjectUser;
import com.mdata.model.po.User;
import com.tencent.wework.Finance;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/openApi")
@RestController
public class LoginController {


    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public ResultData login(String userName, String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try{
            subject.login(token);
        }catch (DefinitionException exception){
            return ResultData.error(ResponseEnum.INSIDE_WRONG_USER_NAME_AND_PASSWORD);
        }

        // 构建缓存用户信息返回给前端
        SubjectUser subjectUser = (SubjectUser) subject.getPrincipals().getPrimaryPrincipal();
        CacheUser cacheUser = CacheUser.builder()
                .token(subject.getSession().getId().toString())
                .id(subjectUser.getId())
                .build();

        // 一个账号只能一个人登录
        String key = RedisKeyConstant.LOGIN_USER_TOKEN + subjectUser.getId();
        if(redisTemplate.hasKey(key)){
            redisTemplate.delete(RedisKeyConstant.SESSION_KEY_PREFIX + redisTemplate.opsForValue().get(key));
            redisTemplate.delete(key);
        }
        redisTemplate.opsForValue().set(key, cacheUser.getToken());

        return ResultData.success(cacheUser);
    }

    @GetMapping("/logout")
    public ResultData logout() {
        Subject subject = SecurityUtils.getSubject();
//        // TODO 先退出时候注销一下
//        SubjectUser subjectUser = (SubjectUser) subject.getPrincipal();
//        Finance.DestroySdk(subjectUser.getFinanceSdk());
        subject.logout();
        return ResultData.success();
    }

    @GetMapping("/toLogin")
    public ResultData toLogin(){
        return ResultData.error(ResponseEnum.NO_AUTH);
    }

    @GetMapping("/unauthorized")
    public ResultData unauthorized(){
        return ResultData.error(ResponseEnum.NO_PERMISSION);
    }
}
